package com.ansion.extension;

import android.os.Looper;
import android.os.MessageQueue;

import com.ansion.log.VLog;

import java.util.LinkedList;
import java.util.Queue;


/***
 * 建议的delay init task dispatcher
 */
public class DelayInitDispatcher {
    private static volatile DelayInitDispatcher instance;

    public static DelayInitDispatcher getInstance() {
        if (instance == null) {
            synchronized (DelayInitDispatcher.class) {
                if (instance == null)
                    instance = new DelayInitDispatcher();
            }
        }
        return instance;
    }

    private final Queue<Runnable> mDelayTasks = new LinkedList<>();

    private MessageQueue.IdleHandler mIdleHandler;

    private MessageQueue.IdleHandler getIdleHandler() {
        if (mIdleHandler == null) {
            mIdleHandler = new MessageQueue.IdleHandler() {
                @Override
                public boolean queueIdle() {
                    if (mDelayTasks.size() > 0) {
                        Runnable task = mDelayTasks.poll();
                        if (task != null)
                            task.run();
                    }
                    return !mDelayTasks.isEmpty();
                }
            };
        }
        return mIdleHandler;
    }

    public DelayInitDispatcher addTask(Runnable task) {
        mDelayTasks.add(task);
        return this;
    }

    boolean isStarted = false;

    public synchronized void start() {
        if (!isStarted) {
            isStarted = true;
            //确保addIdleHandler只调用一次，避免多次调用出现任务执行重复
            VLog.i("APP_START", "start delay init task");
            Looper.myQueue().addIdleHandler(getIdleHandler());
        }
    }

    public synchronized void logout(){
        isStarted = false;
    }

}
